package com.gouqi.bookdemobackend.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gouqi.bookdemobackend.common.ErrorCode;
import com.gouqi.bookdemobackend.exception.BusinessException;
import com.gouqi.bookdemobackend.mapper.BookMapper;
import com.gouqi.bookdemobackend.mapper.UserMapper;
import com.gouqi.bookdemobackend.model.dto.BookQueryRequest;
import com.gouqi.bookdemobackend.model.entity.Book;
import com.gouqi.bookdemobackend.model.entity.User;
import com.gouqi.bookdemobackend.model.vo.BookVO;
import com.gouqi.bookdemobackend.service.BookService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description 针对表【book】的数据库操作Service实现
 */
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book>
        implements BookService {

    @Resource
    private UserMapper userMapper;

    @Override
    public QueryWrapper<Book> getQueryWrapper(BookQueryRequest bookQueryRequest) {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        if (bookQueryRequest == null) {
            return queryWrapper;
        }
        String name = bookQueryRequest.getName();
        String userName = bookQueryRequest.getUserName();
        String sortField = bookQueryRequest.getSortField();
        String userId = null;
        if (StringUtils.isNotBlank(userName)) {
            QueryWrapper<User> wrapper = new QueryWrapper<>();
            wrapper.eq("name", userName);
            User user = userMapper.selectOne(wrapper);
            if (user != null) {
                userId = user.getId();
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "查询为空");
            }
        }
        // 拼接查询条件
        queryWrapper.like(StringUtils.isNotBlank(name), "name", name);
        queryWrapper.like(StringUtils.isNotBlank(userId), "userId", userId);
        return queryWrapper;
    }

    @Override
    public Page<BookVO> getBookVOPage(Page<Book> bookPage, HttpServletRequest request) {
        List<Book> bookList = bookPage.getRecords();
        Page<BookVO> bookVOPage = new Page<>(bookPage.getCurrent(), bookPage.getSize(), bookPage.getTotal());
        if (CollectionUtils.isEmpty(bookList)) {
            return bookVOPage;
        }
        List<BookVO> bookVOList = bookList.stream().map(book -> {
            BookVO bookVO = new BookVO();
            BeanUtil.copyProperties(book, bookVO);
            return bookVO;
        }).collect(Collectors.toList());
        bookVOPage.setRecords(bookVOList);
        return bookVOPage;
    }
}




